package cn.rukbat.demo3.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

@Component
public class SecureUrlBuilder {
    
    @Autowired
    private PasswordlessTokenUtil tokenUtil;
    
    @Value("${app.security.pre-shared-key}")
    private String preSharedKey;
    
    /**
     * 构建免密码安全资源URL
     */
    public String buildSecureResourceUrl(String resourcePath) {
        Long timestamp = System.currentTimeMillis();
        String token = tokenUtil.generateToken(resourcePath, timestamp);
        
        return buildUrl(resourcePath, timestamp, token);
    }
    
    /**
     * 使用预共享密钥构建安全URL（供外部系统调用）
     */
    public String buildSecureResourceUrlWithPSK(String resourcePath, String clientId) {
        Long timestamp = System.currentTimeMillis();
        String token = tokenUtil.generateTokenWithPSK(resourcePath, timestamp, clientId);
        
        return buildUrl(resourcePath, timestamp, token);
    }
    
    /**
     * 构建批量安全URL
     */
    public String buildBatchSecureUrls(String baseUrl, String[] resourcePaths) {
        Long timestamp = System.currentTimeMillis();
        StringBuilder urls = new StringBuilder();
        
        for (String path : resourcePaths) {
            String token = tokenUtil.generateToken(path, timestamp);
            String secureUrl = buildFullUrl(baseUrl, path, timestamp, token);
            urls.append(secureUrl).append("\n");
        }
        
        return urls.toString();
    }
    
    private String buildUrl(String resourcePath, Long timestamp, String token) {
        return UriComponentsBuilder.fromPath(resourcePath)
                .queryParam("t", timestamp)
                .queryParam("token", token)
                .build()
                .toString();
    }
    
    private String buildFullUrl(String baseUrl, String resourcePath, Long timestamp, String token) {
        return UriComponentsBuilder.fromHttpUrl(baseUrl)
                .path(resourcePath)
                .queryParam("t", timestamp)
                .queryParam("token", token)
                .build()
                .toString();
    }
}
